package hk.hku.hooku.util;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import hk.hku.hooku.pojo.*;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.GroupMembershipInfo;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.FamilyName;
import com.google.gdata.data.extensions.FullName;
import com.google.gdata.data.extensions.GivenName;
import com.google.gdata.data.extensions.Im;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.ServiceException;

public class GoogleContactsAccess {

	/*
	 * This method will authenticate the user credentials passed to it and
	 * returns an instance of ContactService class.
	 */

	public ContactsService authenticateId(String userid, String password) {

		ContactsService contactService = null;
		try {
			contactService = new ContactsService("RupalMindfire-AddressApp");
			contactService.setUserCredentials(userid, password);
			// this.userId = userid;
		} catch (Exception e) {
			System.out.println(e);
		}
		return contactService;

	}
	public static ArrayList<Contact> getGmailContacts(String username,
			String gmailPassword) throws IOException, ServiceException {
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		GoogleContactsAccess googleContactsAccess = new GoogleContactsAccess();
		ContactsService contactSrv = googleContactsAccess.authenticateId(username, gmailPassword);
		int lastPageEntryCount = 25;
		URL feedUrl = null;
		ContactFeed resultFeed = null;
		while (lastPageEntryCount == 25) {
			if (feedUrl == null) {
				feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
			}
			else {
				feedUrl = new URL(resultFeed.getNextLink().getHref());
			}
			resultFeed = contactSrv.getFeed(feedUrl, ContactFeed.class);
			lastPageEntryCount = resultFeed.getEntries().size();
			for (int i = 0; i < lastPageEntryCount; i++) {
				String fullNameToDisplay = null;
				String emailAddress = null;
				ContactEntry entry = resultFeed.getEntries().get(i);
				if (entry.hasName()) {
					Name name = entry.getName();
					if (name.hasFullName()) {
						fullNameToDisplay = name.getFullName().getValue();
					}
				}
				for (Email email : entry.getEmailAddresses()) {
					emailAddress = email.getAddress();
					break;
				}
				if (fullNameToDisplay != null && fullNameToDisplay.length() > 0 && emailAddress != null && emailAddress.length() > 0) {
					Contact contact = new Contact(emailAddress, fullNameToDisplay);
					contacts.add(contact);
				}
			}
		}
		return contacts;
	}

}
